package com.bosi.dalian.asp;

import com.bosi.dalian.config.DataSourceConfig;
import com.bosi.dalian.config.DataSourceContextHolder;
import com.bosi.dalian.config.DataSourceSet;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

@Slf4j
@Aspect
@Component
public class DynamicDataSourceAspect {

    @Pointcut("@annotation(com.bosi.dalian.config.DataSourceSet)")
    private void aspect() {}

    @Before("aspect()")
    public void  around(JoinPoint joinPoint) throws Throwable {
        String method = joinPoint.getSignature().getName();
        DataSourceSet dataSourceSet = getAnnotation(joinPoint);
        log.info("切换数据源：{}",dataSourceSet.value());
        DataSourceContextHolder.setDataSource(dataSourceSet.value());
//        try {
//            return joinPoint.proceed();
//        }finally {
//            log.info("清除 datasource router...");
//            DataSourceContextHolder.clear();
//        }
    }


    private DataSourceSet getAnnotation(JoinPoint joinPoint) {
        try {
            // 获取方法签名
            String methodName = joinPoint.getSignature().getName();
            // 获取方法参数类型
            Class<?>[] parameterTypes = ((org.aspectj.lang.reflect.MethodSignature) joinPoint.getSignature()).getMethod().getParameterTypes();
            // 获取目标方法
            java.lang.reflect.Method method = joinPoint.getTarget().getClass().getMethod(methodName, parameterTypes);
            // 获取方法上的注解
            return method.getAnnotation(DataSourceSet.class);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException("Method not found", e);
        }
    }
}